const got = require('got')
const cheerio = require('cheerio');
exports.main = async(event, context) => {
  var isbn = event.isbn
  var bookinfo={}
  var res= await got('https://book.douban.com/isbn/' + isbn)
    .then(response => {
      html = response.body
      const $ = cheerio.load(html)
      title = $('#wrapper h1').text().replace(/ /g, '').replace(/\n/g, '') //获取书名
      image_url = $('.nbg').attr('href') //获取图片地址
      introduce = $('#link-report div').last().text().replace(/ /g, ''); //获取内容简介
      info = $('#info').text().replace(/ /g, ''); //获取数目信息
      for (var i = 0; i < 12; i++) {
        info = info.replace("\n", '').replace(":\n", ':').replace("//", ';');
      }
      //console.log(info)
      info = info.split('\n')
      var str = "";
      for (var i = 0, j = 0; i < info.length; i++) {
        if (info[i] != '' && info[i].indexOf(':') != -1) {
          if (j == 0)
            info[i] = '"' + info[i].replace(":", '":"') + '"';
          else
            info[i] = ',"' + info[i].replace(":", '":"') + '"';
          j++
          str = str + info[i]
        }
      }
      str = '{' + str + '}'
      console.log(str)
      bookinfo = JSON.parse(str)
      bookinfo.title = title
      bookinfo.url = image_url
      bookinfo.内容简介 = introduce
      bookinfo.status=1
      console.log(bookinfo)
      return bookinfo
    })
    .catch(error => {
      //console.log(error.response.body);
      console.log("豆瓣没有收录此书")
      bookinfo.status=0
      return bookinfo
    });
  return res
}